import React, { useState, useEffect, memo, useRef } from "react";
import { useModel } from "umi";
/* eslint-disable no-unused-vars */
import { CaretRightOutlined } from "@ant-design/icons";
import {
  Collapse,
  theme,
  Form,
  Button,
  Input,
  Switch,
  Empty,
  Drawer,
  Slider,
} from "antd";
import DraggableControl from "@/components/DragContainer";
import {
  LightFilter,
  ProForm,
  ProFormSwitch,
  ProFormText,
  ProFormDigit,
  ProFormSelect,
  ProFormDependency,
  ProFormSlider,
} from "@ant-design/pro-components";
import Grider from "@/components/Grider";

const text = `
  A dog is a type of domesticated animal.
  Known for its loyalty and faithfulness,
  it can be found as a welcome guest in many households across the world.
`;

const sizes = ["xs", "sm", "md", "lg", "xl", "xxl"];

const baseconfig = [];

const layout = {
  labelCol: { span: 12 },
  wrapperCol: { span: 12 },
};

const FormAttr = memo(() => {
  const formRef = useRef();
  const {
    initialState: { activeItem, updateTemplate },
    setInitialState,
  } = useModel("@@initialState");

  const handleChange = (allval) => {
    setInitialState((s) => {
      return {
        ...s,
        activeItem: {
          ...s.activeItem,
          ...allval,
        },
      };
    });
  };

  useEffect(() => {
    formRef?.current?.setFieldsValue(activeItem);
  }, [updateTemplate, formRef]);

  return (
    <div className="column diyform" style={{ gap: 16 }}>
      <ProForm
        formRef={formRef}
        submitter={false}
        layout="horizontal"
        size="small"
        variant="filled"
        {...layout}
        onValuesChange={(val, allval) => {
          let res = { ...allval, name: allval.name || "s" };
          if (Object.keys(val).includes("required")) {
            res.rules = val.required
              ? [
                  ...(res.rules || []),
                  {
                    required: true,
                    message: `${allval.label}为必填项`,
                  },
                ]
              : res?.rules?.filter?.((it) => !it.required);
          } else {
          }

          handleChange(res);
        }}
      >
        <ProFormText
          name="label"
          colon={false}
          labelAlign="left"
          label="名称-label"
          rules={[{ required: true, message: "" }]}
        />
        <ProFormText
          name="name"
          colon={false}
          labelAlign="left"
          label="参数-name"
          rules={[{ required: true, message: "" }]}
        />
        <ProFormSwitch
          name="required"
          colon={false}
          labelAlign="left"
          label="必填-required"
        />
        <ProFormSwitch
          name="readonly"
          colon={false}
          labelAlign="left"
          label="只读-readonly"
        />
        <ProFormText
          name="tooltip"
          colon={false}
          labelAlign="left"
          label="帮助-tooltip"
        />
        <ProFormText
          name="extra"
          colon={false}
          labelAlign="left"
          label="额外说明-extra"
        />
      </ProForm>
    </div>
  );
});

const BaseAttr = memo(() => {
  const formRef = useRef();
  const {
    initialState: { activeItem, updateTemplate },
    setInitialState,
  } = useModel("@@initialState");

  const handleChange = (allval) => {
    setInitialState((s) => {
      return {
        ...s,
        activeItem: {
          ...s.activeItem,
          ...allval,
        },
      };
    });
  };

  useEffect(() => {
    formRef?.current?.setFieldsValue(activeItem);
  }, [updateTemplate, formRef]);

  return (
    <div className="column diyform" style={{ gap: 16 }}>
      <ProForm
        formRef={formRef}
        submitter={false}
        layout="horizontal"
        size="small"
        variant="filled"
        {...layout}
        onValuesChange={(val, allval) => {
          handleChange({
            fieldProps: {
              ...allval,
            },
          });
        }}
      >
        <ProFormDigit
          name="maxLength"
          colon={false}
          labelAlign="left"
          label="长度-maxLength"
        />
        <ProFormDependency name={["maxLength"]}>
          {({ maxLength }) => {
            return (
              <ProFormSwitch
                name="showCount"
                colon={false}
                labelAlign="left"
                label="显示-showCount"
                hidden={!maxLength}
              />
            );
          }}
        </ProFormDependency>

        <ProFormText
          name="placeholder"
          colon={false}
          labelAlign="left"
          label="占位-placeholder"
        />

        <ProFormSwitch
          name="disabled"
          colon={false}
          labelAlign="left"
          label="禁用-disabled"
        />
        <ProFormSwitch
          name="allowClear"
          colon={false}
          labelAlign="left"
          label="可清除-allowClear"
        />
      </ProForm>
    </div>
  );
});

const Template = ({ form }) => {
  const {
    initialState: { activeItem, auto },
    setInitialState,
  } = useModel("@@initialState");

  // const curvalue = Form.useWatch(activeItem?.name, { form });

  const { token } = theme.useToken();
  const panelStyle = {
    margin: 0,
    border: "none",
  };

  const [drawer, setDrawer] = useState({
    open: false,
  });

  console.log("====================================");
  console.log(activeItem);
  console.log("====================================");

  //更新table组件
  useEffect(() => {
    setInitialState((s) => {
      return {
        ...s,
        formControls: s.formControls.map((it) => {
          if (it.name === activeItem.name) {
            return {
              ...it,
              ...activeItem,
            };
          }
          return it;
        }),
      };
    });
  }, [activeItem]);

  return (
    <div>
      <Drawer
        {...drawer}
        onClose={() => {
          setDrawer((s) => ({
            ...s,
            open: false,
          }));
        }}
        closable={false}
        width={260}
      >
        asd
      </Drawer>
      {activeItem?.name ? (
        <Collapse
          bordered={false}
          defaultActiveKey={["1", "2", "3", "4"]}
          expandIcon={({ isActive }) => (
            <CaretRightOutlined rotate={isActive ? 90 : 0} />
          )}
          style={{
            background: token.colorBgContainer,
            margin: "0 12px",
          }}
          items={[
            {
              key: "0",
              label: (
                <div className="spread">
                  <b>布局配置</b>
                </div>
              ),
              children: (
                <div>
                  <Grider changeKey={"activeItem"}></Grider>
                </div>
              ),
              style: panelStyle,
            },
            {
              key: "1",
              label: (
                <div className="spread">
                  <b>表单属性</b>
                  <a
                    style={{ fontSize: 12, fontWeight: "lighter" }}
                    onClick={(e) => {
                      e.stopPropagation();
                      setDrawer((s) => ({
                        ...s,
                        title: "更多表单属性",
                        open: true,
                      }));
                    }}
                  >
                    更多
                  </a>
                </div>
              ),
              children: <FormAttr></FormAttr>,
              style: panelStyle,
            },
            {
              key: "2",
              label: "基础字段",
              children: <BaseAttr></BaseAttr>,
              style: panelStyle,
            },
            {
              key: "3",
              label: "高级字段",
              children: <p>{text}</p>,
              style: panelStyle,
            },
            {
              key: "4",
              label: "提交数据",
              children: (
                <div>
                  <Button
                    onClick={() => {
                      console.log("====================================");
                      console.log(form.getFieldsValue());
                      console.log("====================================");
                    }}
                  >
                    ann
                  </Button>
                </div>
              ),
              style: panelStyle,
            },
          ]}
        />
      ) : (
        <Empty description="请选择组件" style={{ marginTop: 120 }}></Empty>
      )}
    </div>
  );
};

export default memo(Template);
